package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.search.constant.EsConstant;
import com.hmall.search.pojo.ItemDto;
import com.hmall.search.pojo.PageResult;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceimpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public List<String> suggestion(String key) {

        try {
            //准备SearchRequest
            SearchRequest request = new SearchRequest(EsConstant.Itme_INDEX);
            //准备DSL
            request.source().suggest(
                    new SuggestBuilder()
                            .addSuggestion(
                                    "search_suggest",
                                    new CompletionSuggestionBuilder("suggestion")
                                            .prefix(key)
                                            .skipDuplicates(true)
                                            .size(10)
                            )
            );
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            ArrayList<String> arrayList = new ArrayList<>();
            CompletionSuggestion suggestion = response.getSuggest().getSuggestion("search_suggest");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                arrayList.add(text);
                return arrayList;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {

        try {
            //1.创建SearchRequest
            SearchRequest request = new SearchRequest(EsConstant.Itme_INDEX);

            //过滤条件
            queryCondition(params, request);

            //聚合
            //品牌聚合
            aggByName(request, "brandAgg", "brand", 10);
            //分类聚合
            aggByName(request, "categoryAgg", "category", 10);

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //处理结果
            Map<String, List<String>> resultMap = new HashMap<>();

            List<String> brandList = getListByAggName(response, "brandAgg");
            resultMap.put("brand", brandList);

            List<String> categoryList = getListByAggName(response, "categoryAgg");
            resultMap.put("category", categoryList);

            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new HashMap<>();
    }

    /*
    基本搜索功能
     */
    @Override
    public PageResult<ItemDto> list(RequestParams params) {

        PageResult<ItemDto> itemDtoPageResult = new PageResult<>();
        try {
            SearchRequest request = new SearchRequest(EsConstant.Itme_INDEX);

            queryCondition(params, request);
            //排序
            String sortBy = params.getSortBy();
            if ("score".equals(sortBy)) {
                request.source().sort("score", SortOrder.DESC);
            } else if ("price".equals(sortBy)) {
                request.source().sort("price", SortOrder.DESC);
            }

            //分页
            Integer page = params.getPage(); //当前页
            Integer size = params.getSize(); //页大小
            request.source()
                    .from((page - 1) * size)
                    .size(size)
                    .highlighter(
                           new HighlightBuilder()
                                   .field("name")
                                   .field("brand")
                                   .requireFieldMatch(false)
                    )
            ;

            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            SearchHits searchHits = response.getHits();

            //获取总条数
            long total = searchHits.getTotalHits().value;

            List<ItemDto> itemDtos = handleResponse(response);

            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                ItemDto itemDto = JSON.parseObject(json, ItemDto.class);
                //获取高亮字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields!=null&&highlightFields.size()>0){
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField!=null){
                    //获取高亮字段key值,并转化为字符串
                        String name = highlightField.getFragments()[0].toString();
                        itemDto.setName(name);
                    }
                }

            }

            itemDtoPageResult = new PageResult<>(itemDtos, total);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return itemDtoPageResult;
    }


    /**
     * 处理结果
     *
     * @param response
     * @return
     */
    private List<ItemDto> handleResponse(SearchResponse response) {
        List<ItemDto> itemDtoList = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();

            ItemDto itemDtoDoc = JSON.parseObject(json, ItemDto.class);

            itemDtoList.add(itemDtoDoc);
        }
        return itemDtoList;
    }

    /**
     * 桶聚合条件
     *
     * @param request
     * @param aggName   聚合名称
     * @param fieldName 聚合字段
     * @param size      获取条数
     */
    private void aggByName(SearchRequest request, String aggName, String fieldName, Integer size) {
        request.source()
                .size(0)
                .aggregation(
                        AggregationBuilders
                                .terms(aggName)
                                .field(fieldName)
                                .size(size)
                );
    }

    /**
     * 根据聚合名称获取结果【集合】
     *
     * @param response
     * @param aggName
     * @return
     */
    private List<String> getListByAggName(SearchResponse response, String aggName) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : brandAggBuckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    /**
     * 封装查询条件
     *
     * @param params
     * @param request
     */
    private void queryCondition(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //搜索框 all
        String key = params.getKey();
        if (key != null && !"".equals(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        //品牌
        String brand = params.getBrand();
        if (brand != null && !"".equals(brand)) {
            boolQuery.must(QueryBuilders.termQuery("brand", brand));
        }

        //种类
        String category = params.getCategory();
        if (category != null && !"".equals(category)) {
            boolQuery.must(QueryBuilders.termQuery("category", category));
        }

        //价格
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(
                    QueryBuilders.rangeQuery("price")
                            .gte(minPrice)
                            .lte(maxPrice)
            );
        }

        //做广告：为isAD是true的增加分数
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                                // 原始查询，相关性算分的查询
                                boolQuery,
                                // function score的数组
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                        // 其中的一个function score 元素
                                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                                // 过滤条件
                                                QueryBuilders.termQuery("isAD", true),
                                                // 算分函数
                                                ScoreFunctionBuilders.weightFactorFunction(100)
                                        )
                                })
                        //算分方式，现在是求和
                        .boostMode(CombineFunction.SUM);
        //2.1.2 封装查询条件
        request.source().query(functionScoreQuery);
    }


}
